package com.android.settings.audio.peq.qr.decoder;

import static com.android.settings.audio.peq.qr.Constant.QR_SCHEMA_V1_EQ;

import android.text.TextUtils;

import com.android.settings.audio.peq.qr.QrManager;
import com.android.settings.audio.peq.qr.annotation.QrImpl;
import com.android.settings.audio.peq.soundeffect.PluginDataManager;
import com.android.settings.audio.peq.util.Base64;
import com.android.settings.audio.peq.util.ByteUtil;


/**
 * Created by We on 2023/5/24
 */
@QrImpl(id = QR_SCHEMA_V1_EQ)
public class EqV1Decoder extends QrManager.AbsDecoder {
    public EqV1Decoder() {
        this.id = QR_SCHEMA_V1_EQ; //by inject
    }

    @Override
    public boolean canDecode(String content) {
        return content.startsWith(this.id);
    }

    @Override
    public Object onDecoded(String content) {
        //todo 解析二维码内容&动作
        if (TextUtils.isEmpty(content)) {
            throw new IllegalArgumentException("str is null");
        }
        content = content.substring(this.id.length());
        int readIndex = 0;
        byte[] data = Base64.decode(content);

        int nameLen = data[readIndex++] & 0xFF;

        byte[] nameBytes = new byte[nameLen];
        System.arraycopy(data, readIndex, nameBytes, 0, nameBytes.length);
        readIndex += nameBytes.length;

        int deviceBytesLen = data[readIndex++] & 0xFF;

        byte[] deviceBytes = new byte[deviceBytesLen];
        System.arraycopy(data, readIndex, deviceBytes, 0, deviceBytes.length);
        readIndex += deviceBytes.length;

        int descriptionBytesLen = data[readIndex++] & 0xFF;

        byte[] descriptionBytes = new byte[descriptionBytesLen];
        System.arraycopy(data, readIndex, descriptionBytes, 0, descriptionBytes.length);
        readIndex += descriptionBytes.length;

        int progressesLen = data[readIndex++] & 0xFF;

        float[] progresses = new float[progressesLen];

        for (int i = 0; i < progressesLen; ++i) {
            byte[] progressBytes = new byte[4];
            System.arraycopy(data, readIndex, progressBytes, 0, progressBytes.length);
            readIndex += progressBytes.length;
            progresses[i] = ByteUtil.convertToFloat(progressBytes);
        }
        PluginDataManager.EqData eqData = new PluginDataManager.EqData();
        eqData.name = new String(nameBytes);
        eqData.device = new String(deviceBytes);
        eqData.description = new String(descriptionBytes);
        eqData.value = (progresses);
        return eqData;
    }
}
